﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ElectronicScale
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private SerialPort serialPort;

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var guid = config.AppSettings.Settings["GUID"].Value;
                var serialPort = config.AppSettings.Settings["SerialPort"].Value;
                var databaseEnable = config.AppSettings.Settings["DatabaseEnable"].Value;
                var dbAddress = config.AppSettings.Settings["DBAddress"].Value;
                var dbName = config.AppSettings.Settings["DBName"].Value;
                var dbUid = config.AppSettings.Settings["DBUid"].Value;
                var dbPwd = config.AppSettings.Settings["DBPwd"].Value;
            }
            catch (Exception)
            {
                MessageBox.Show("加载配置文件出现错误","",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }


            

            GetComList();
        }

        #region 从注册表获取系统串口列表
        /// <summary> 
        /// 从注册表获取系统串口列表 
        /// </summary> 
        private void GetComList()
        {
            //string[] portList = System.IO.Ports.SerialPort.GetPortNames();

            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                this.comboBox1.Items.Clear();
                foreach (string sName in sSubKeys)
                {
                    string sValue = (string)keyCom.GetValue(sName);
                    this.cbbSerialPort.Items.Add(sValue);
                }
            }
        } 
        #endregion

        private byte[] buffer = new byte[1024];

        private DateTime lastDateTime = DateTime.Now;

        private int index = 1;

        private string lastWeight = string.Empty;

        
        private void DataResived(object sender, SerialDataReceivedEventArgs e)
        {
            //DateTime dtOld = System.DateTime.Now;

            int count = serialPort.Read(buffer,0, buffer.Length);

            if (count>12)
            {
                try
                {
                    serialPort.ReadExisting();
                }
                catch (Exception)
                {
                }
            }

            if (count > 0)
            {
                List<byte> dataBytes = new List<byte>(12);
                bool flagStart = false;
                bool flagEnd = false;

                for (int i = 0; i < count; i++)
                {
                    if (buffer[i] == 2)
                    {
                        dataBytes = new List<byte>(12);
                        flagStart = true;
                        flagEnd = false;
                    }
                    else if (buffer[i] == 3)
                    {
                        flagEnd = true;
                        flagStart = false;
                    }

                    if (flagStart)
                    {
                        dataBytes.Add(buffer[i]);
                    }
                    else if (flagEnd)
                    {
                        dataBytes.Add(buffer[i]);
                        if (dataBytes.Count==12)
                        {
                           TimeSpan dtInter = DateTime.Now - lastDateTime;

                            var data = Encoding.ASCII.GetString(dataBytes.ToArray(),2,6);
                            var point = Encoding.ASCII.GetString(dataBytes.ToArray(), 8, 1);

                            var weight = data.Insert(data.Length- int.Parse(point), ".");

                            if (dtInter.TotalSeconds> 5)
                            {
                                ListViewItem lvi = new ListViewItem();
                                lvi.SubItems.Add(index.ToString());
                                lvi.SubItems.Add(lastDateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                                lvi.SubItems.Add(weight);
                                this.Invoke(new Action(() => listView1.Items.Add(lvi)));
                                index++;
                            }
                            lastWeight = weight;
                            txtContext.Text = "当前重量：" + weight;
                        }
                    }
                    
                    
                }
            }

            lastDateTime = DateTime.Now;
        }

        private void DevicePortError_DataReceived(object sender, SerialErrorReceivedEventArgs e)
        {
            MessageBox.Show(e.EventType.ToString());
        }

        private void btnListen_Click(object sender, EventArgs e)
        {
            if ((this.cbbSerialPort.Text.Trim() != "") && (this.comboBox1.Text != ""))
            {
                try
                {
                    serialPort = new SerialPort(this.cbbSerialPort.Text.Trim());
                    //serialPort.PortName = this.cbbSerialPort.Text.Trim();
                    serialPort.BaudRate = Convert.ToInt32(this.comboBox1.Text.Trim());
                    serialPort.Parity = Parity.None;
                    serialPort.StopBits = StopBits.One;
                    serialPort.DataBits = 8;
                    serialPort.Encoding = Encoding.ASCII;
                    serialPort.DataReceived += new SerialDataReceivedEventHandler(DataResived);

                    serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(DevicePortError_DataReceived);
                    

                    serialPort.ReceivedBytesThreshold = 12;
                    if (serialPort.IsOpen)
                    {
                        serialPort.Close();
                    }
                    serialPort.Open();

                    lastDateTime = DateTime.Now;

                    btnListen.Enabled = false;
                    btPause.Enabled = true;
                }
                catch
                {
                    MessageBox.Show("端口" + this.cbbSerialPort.Text.Trim() + "打开失败！");
                }
            }
            else
            {
                MessageBox.Show("请输入正确的端口号和波特率！");
                this.cbbSerialPort.Focus();
            }
        }
    }
}
